package com.huangd.platform.modules.sys.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huangd.platform.modules.sys.dao.TblUserDao;
import com.huangd.platform.modules.sys.entity.TblRoleEntity;
import com.huangd.platform.modules.sys.entity.TblUserEntity;
import com.huangd.platform.modules.sys.entity.to.SetUserTagTo;
import com.huangd.platform.common.utils.PageUtils;
import com.huangd.platform.common.utils.Query;
import com.huangd.platform.common.utils.R;
import com.huangd.platform.datasource.annotation.DataSource;
import com.huangd.platform.modules.sys.service.TblRoleService;
import com.huangd.platform.modules.sys.service.TblUserRoleService;
import com.huangd.platform.modules.sys.service.TblUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service("tblUserService")
@DataSource("platform")
public class TblUserServiceImpl extends ServiceImpl<TblUserDao, TblUserEntity> implements TblUserService {
    @Resource
    private TblUserRoleService sysUserRoleService;
    @Resource
    private TblRoleService roleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String username = (String)params.get("username");

        IPage<TblUserEntity> page = this.page(
                new Query<TblUserEntity>().getPage(params),
                new QueryWrapper<TblUserEntity>()
                        .like(StringUtils.isNotBlank(username),"username", username)
        );

        return new PageUtils(page);
    }

    @Override
    public List<String> queryAllPerms(Long userId) {
        return baseMapper.queryAllPerms(userId);
    }

    @Override
    public List<Integer> queryAllMenuId(Integer userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public TblUserEntity queryByUserName(String username) {
        return baseMapper.queryByUserName(username);
    }

    @Override
    @Transactional
    public void saveUser(TblUserEntity user) {
        user.setCreateDate(new Date());
        //md5加密
        user.setPassword(SecureUtil.md5(user.getPassword()));
        this.save(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getId(), user.getRoleIdList());
    }

    @Override
    @Transactional
    public void update(TblUserEntity user) {
        if(StringUtils.isBlank(user.getPassword())){
            user.setPassword(null);
        }else{
            user.setPassword(SecureUtil.md5(user.getPassword()));
        }
        this.updateById(user);


        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getId(), user.getRoleIdList());
    }

    @Override
    public void deleteBatch(Long[] userId) {
        // 先删除角色表
        for (Long uid : userId) {
            sysUserRoleService.deletebyId(Math.toIntExact(uid));
        }

        this.removeByIds(Arrays.asList(userId));
    }

    @Override
    public boolean updatePassword(Integer userId, String password, String newPassword) {
        TblUserEntity userEntity = new TblUserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
                new QueryWrapper<TblUserEntity>().eq("id", userId).eq("password", password));
    }

    @Override
    public R updateTag(SetUserTagTo userTagTo) {
        Integer userId = userTagTo.getUserId();
        List<Integer> tags = userTagTo.getTags();
        if (userId == null) {
            return R.error("uid 不能为空");
        }
        TblUserEntity userEntity = baseMapper.selectById(userId);
        if (userEntity == null) {
            return R.error("没有该用户");
        }
        String tagJson = JSON.toJSONString(tags);
        userEntity.setCommonTag(tagJson);
        baseMapper.updateById(userEntity);
        return R.ok();
    }

    @Override
    public TblUserEntity getByUid(Long userId) {
        TblUserEntity user = baseMapper.selectById(userId);
        //获取用户所属的角色列表
        List<Integer> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        // 获得所有角色
        List<TblRoleEntity> list = roleService.list();
        Map<Long, String> map = list.stream().collect(Collectors.toMap(TblRoleEntity::getId, TblRoleEntity::getName));
        List<String> roleNames = new ArrayList<>();
        Map<Long, String> mapCode = list.stream().collect(Collectors.toMap(TblRoleEntity::getId, TblRoleEntity::getCode));
        List<String> roleCodes = new ArrayList<>();
        for (Integer roleId : roleIdList) {
            roleNames.add(map.get((long)roleId));
            roleCodes.add(mapCode.get((long)roleId));
        }
        if (user != null) {
            user.setRoleNames(roleNames);
            user.setRoleIdList(roleIdList);
            user.setRoleCodes(roleCodes);
            return user;
        } else  {
            return new TblUserEntity();
        }
    }

    @Override
    public Map<Integer, TblUserEntity> getAll() {
        List<TblUserEntity> list = baseMapper.getAll();
        Map<Integer, TblUserEntity> map = new HashMap<>();
        for (TblUserEntity userEntity : list) {
            map.put(userEntity.getId(), userEntity);
        }
        return map;
    }
}